-- dragon
-- created by panyl
-- 标记一个怪物位置，降低其攻击和生命，击杀概率获得龙珠

return {
    apply = function(prop, baseValue)
        return baseValue - math.floor(baseValue * tonumber(prop[2]) / 1000);
    end,

    -- 攻击时触发
    trigger = function(who, prop, arg)
        -- 玩家触发
        if who.type == OBJECT_TYPE_USER then

            -- 副本、boss、神龙夹层都忽略
            local layer = DungeonM.currentLayer();
            local dungeonId = DungeonM.getDungeonId();
            if DungeonInstanceM.isInInstance() or
                DungeonBossM.isBossLayer(dungeonId, layer) or
                UnrealDungeonM.isInUnreal() then
                return;
            end

            local arr = {};
            local grid;
            for pos = 1, GRID_SIZE do
                grid = DungeonM.getGridByPos(pos);

                local monster = grid.monster;

                -- 如果是未翻开的怪物
                if not grid:isOpened() and not grid:isPublicGrid()
                    and grid.type == GRID_TYPE_MONSTER and
                    monster and not monster:query("track") then
                    table.insert(arr, grid);
                end
            end

            if #arr <= 0 then
                -- 没有需要标记的怪物
                return true;
            end

            local rand = DungeonM.getRandSeed("dragon") % #arr;

            grid = arr[rand + 1];

            -- 概率
            if DungeonM.getRandSeed("dragon") % 1000 < tonumber(prop[3]) then
                arr = { PropM.getPropId("dragon"), prop[2], prop[3], -1, };

                PropM.record(grid.monster, arr, "mark");
            end

            grid.monster.dbase:set("dragon", true);
            -- 削弱生命
            local currHp = grid.monster:getHp("hp");
            local reduceHp = math.modf(currHp * tonumber(prop[2]) / 1000);
            grid.monster:setRealHp(currHp - reduceHp);

        elseif who.type == OBJECT_TYPE_MONSTER then

            -- -- 概率
            -- if DungeonM.getRandSeed("dragon") % 1000 >= tonumber(prop[3]) then
            --     -- 没发生
            --     return false;
            -- end

            -- TODO: 怪物死亡触发，掉落龙珠
            DungeonLogM.addLog("怪物死亡触发，掉落龙珠。");
            local bonus = {1, 1500, 1};
            BonusM.doBonus(bonus, "dragon");

            -- 效果
            local pos = who.dbase:query("pos");
            if not pos then
                pos = who:getOwner();
            end
            EventMgr.fire(event.PROP_GAIN_DRAGON_BALL, {["bonus"] = bonus,
                ["pos"] = pos, ["newBonus"] = nil, });
        end

        -- 触发特技发动事件
        EventMgr.fire(event.SPECIAL_SKILL_TRIGGER, { propId = prop[1] });

        return true;
    end,

    record = function(target, prop, path)
        return false;
    end
};
